package com.jy.api.service.impl;

import com.jy.api.dao.StockProductDao;
import com.jy.api.dao.StockProductTypeDao;
import com.jy.api.domain.StockProduct;
import com.jy.api.domain.StockProductType;
import com.jy.api.service.StockProductTypeService;
import com.jy.api.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by xiaohua on 2019/4/19.
 */
@Service
public class StockProductTypeServiceImpl implements StockProductTypeService {

   @Autowired
   private StockProductTypeDao typeDao;
   @Autowired
   private StockProductDao productDao;

    @Override
    public List<StockProductType> findAll() {
        return typeDao.findAllByEnabled(true);
    }

    @Override
    public void addOrUpdateProduct(String name, int id) {
        StockProductType type;
        if (id==0){
            type = new StockProductType();
            type.setName(name);
        }else {
            type =typeDao.findOne(id);
            type.setName(name);
        }
        typeDao.save(type);
    }

    @Override
    public Result deleteProduct(int id) {
           StockProductType type= typeDao.findOne(id);
           List<StockProduct>  list = productDao.findAllByProductTypeIdAndEnabled(type.getId(),true);
           if (list.isEmpty()){
               type.setEnabled(false);
               typeDao.save(type);
               return new Result(200,"分类移除成功");
           }else {
                return new Result(400,"该分类下还有商品，核实后进行移除");
           }
    }
}
